package com.tf.xx.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.tf.xx.service.OssService;
import com.tf.xx.util.ConstantPropertiesUtil;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.xml.crypto.Data;
import java.io.InputStream;

@Service
public class OssServiceImpl implements OssService {
        @Override
    public String uploadFileAvatar(MultipartFile file) {
        //工具类获取
        String endpoint = ConstantPropertiesUtil.END_POINT;
        String keyId = ConstantPropertiesUtil.KEY_ID;
        String keySecret = ConstantPropertiesUtil.KEY_SECRET;
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;
        String url = null;

        //输入流
        InputStream inputStream = null;
        try {
            //创建OSS实例
            OSS ossClient = new OSSClientBuilder().build(endpoint, keyId, keySecret);
            //获取文件
            inputStream = file.getInputStream();
            //获取文件名称
            String fileName = file.getOriginalFilename();
            //在文件名称中添加uuid，防止重复
            String uuid = java.util.UUID.randomUUID().toString().replaceAll("-", "");
            fileName = uuid + fileName;
            //把文件按时间分类
            String datePath = new DateTime().toString("yyyy/MM/dd");
            fileName = datePath + "/" + fileName;
            //上传文件
            ossClient.putObject(bucketName, fileName, inputStream);
            //关闭OSSClient
            ossClient.shutdown();
            //上传之后文件路径
            url = "https://" + bucketName + "." + endpoint + "/" + fileName;
            
        } catch (Exception e) {
            e.printStackTrace();
        }

        // TODO: 2020/5/7 上传头像
        return url;
    }
}
